#import "MYRegisterSetPasswordVC.h"

#import "MYRegisterFindPasswordVC.h"
#import "BRStringPickerView.h"
@interface MYRegisterFindPasswordVC ()
@property (nonatomic, assign) NSInteger selectOperateType;

@property (nonatomic, strong) UIButton * codeButton;
@property (nonatomic,strong) Calculagraph *codeTimer;

@property (nonatomic, copy) NSString * mobileAreaCode;
@property (nonatomic, copy) NSString * defaultLocale;
@end

@implementation MYRegisterFindPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectOperateType = 1;
    //二者需一一对应
    self.defaultLocale = @"香港 852";
    self.mobileAreaCode = @"852";
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    MYRegisterFindPasswordCodeCell *codeCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    [codeCell.codeBtn addTarget:self action:@selector(sendCodeClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setupView {
    [super setupView];
    [self.listTableView registerNib:[UINib nibWithNibName:@"MYAccountsCommonHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MYAccountsCommonHeaderView"];
    [self.listTableView registerClass:[MYRegisterFindPasswordTextFieldCell class] forCellReuseIdentifier:@"MYRegisterFindPasswordTextFieldCell"];
    [self.listTableView registerClass:[MYRegisterFindPasswordCodeCell class] forCellReuseIdentifier:@"MYRegisterFindPasswordCodeCell"];
    [self.listTableView registerClass:[MYLoginBaseBtnCell class] forCellReuseIdentifier:@"MYLoginBaseBtnCellNextKey"];
    [self.listTableView registerClass:[MYLoginBaseBtnCell class] forCellReuseIdentifier:@"MYLoginBaseBtnCell"];
    [self.listTableView registerClass:[MYLoginBaseTextFieldPhoneCell class] forCellReuseIdentifier:@"MYLoginBaseTextFieldPhoneCell"];
    
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (self.selectOperateType == 1) {
            MYLoginBaseTextFieldPhoneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseTextFieldPhoneCell"];
            cell.placeholderStr = kYQLS(@"请输入手机号");
            ws(self);
            [cell.leftBgView addTapAction:^(id  _Nonnull sender) {
                [weakself selectPhoneAreaCode];
            }];
            return cell;
        }else{
            MYRegisterFindPasswordTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYRegisterFindPasswordTextFieldCell"];
            cell.placeholderStr = kYQLS(@"请输入邮箱");
            return cell;
        }
    }else if (indexPath.row == 1){
        MYRegisterFindPasswordCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYRegisterFindPasswordCodeCell"];
        cell.placeholderStr = kYQLS(@"请输入验证码");
        self.codeButton = cell.codeBtn;
        return cell;
    }else if (indexPath.row == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kTableViewCell"];
        if (!cell){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"kTableViewCell"];
        }
        cell.contentView.backgroundColor = UIColor.whiteColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if(indexPath.row == 3){
        MYLoginBaseBtnCell *loginCell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseBtnCellNextKey"];
        [loginCell.loginBtn setBackgroundColor:HexColor(0x79C4C7)];
        [loginCell.loginBtn setTitleColor:UIColor.whiteColor forState:(UIControlStateNormal)];
        [loginCell.loginBtn addTarget:self action:@selector(nextAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [loginCell.loginBtn setTitle:kYQLS(@"下一步") forState:(UIControlStateNormal)];
        
        return loginCell;
    }else{
        MYLoginBaseBtnCell *loginTypeCell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseBtnCell"];
        [loginTypeCell.loginBtn setBackgroundColor:UIColor.whiteColor];
        [loginTypeCell.loginBtn setTitleColor:HexColor(0x79C4C7) forState:(UIControlStateNormal)];
        [loginTypeCell.loginBtn addTarget:self action:@selector(selectOperateTypeAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        if (self.selectOperateType == 1) {
            [loginTypeCell.loginBtn setTitle:kYQLS(@"邮箱找回") forState:(UIControlStateNormal)];
        }else{
            [loginTypeCell.loginBtn setTitle:kYQLS(@"手机号找回") forState:(UIControlStateNormal)];
        }
        
        
        return loginTypeCell;
    }
    
    

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 1) {
        return 56;
    }
    if (indexPath.row == 2) {
        return 62;
    }
    return 68;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MYAccountsCommonHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYAccountsCommonHeaderView"];
    headerView.titleLb.text = kYQLS(@"找回密码");
    if (self.selectOperateType == 1) {
        headerView.subheadLb.text = kYQLS(@"请输入手机账号及验证码");
    }else{
        headerView.subheadLb.text = kYQLS(@"请输入邮箱账号及验证码");
    }

    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 115;
}
#pragma mark - 下一步
-(void)nextAction:(UIButton *)sender {
    MYRegisterFindPasswordTextFieldCell *phoneCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    MYRegisterFindPasswordCodeCell *codeCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];

    if (self.selectOperateType == 1) {
        if (phoneCell.textField.text.length == 0) {
            [MBProgressHUD showSuccess:kYQLS(@"请输入手机号")];
            return;
        }
//        else{
//            BOOL isValuate = [YQPInsureValidate validateMobile:phoneCell.textField.text];
//            if (!isValuate) {
//                [MBProgressHUD showSuccess:@"请输入有效手机号"];
//                return;
//            }
//        }

        NSMutableDictionary *dic = NSMutableDictionary.new;
        dic[@"mobile"] = phoneCell.textField.text;
        dic[@"code"] = codeCell.textField.text;

        [YQPNetWorkingManager sendPostRequest:kPOST_PHONECODE_CHECK_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            [MBProgressHUD showSuccess:responseObject.msg];
            MYRegisterSetPasswordVC *setPasswordVC = [[MYRegisterSetPasswordVC alloc] init];
            setPasswordVC.isBack = YES;
            setPasswordVC.userId = responseObject.data;

            [self.navigationController pushViewController:setPasswordVC animated:true];    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            
        }];
    } else{
        if (phoneCell.textField.text.length == 0) {
            [MBProgressHUD showSuccess:kYQLS(@"请输入邮箱")];
            return;
        }else{
            BOOL isValuate = [YQPInsureValidate validateEmail:phoneCell.textField.text];
            if (!isValuate) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入有效邮箱")];
                return;
            }
        }

        NSMutableDictionary *dic = NSMutableDictionary.new;
        dic[@"email"] = phoneCell.textField.text;
        dic[@"code"] = codeCell.textField.text;

        [YQPNetWorkingManager sendPostRequest:kPOST_EMAILCODE_CHECK_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            [MBProgressHUD showSuccess:responseObject.msg];
            MYRegisterSetPasswordVC *setPasswordVC = [[MYRegisterSetPasswordVC alloc] init];
            setPasswordVC.isBack = YES;
            setPasswordVC.userId = responseObject.data;

            [self.navigationController pushViewController:setPasswordVC animated:true];    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            
        }];
    }
    
}
-(void)selectOperateTypeAction:(UIButton *)sender {
    [self.codeTimer stop];
    self.codeButton.enabled = YES;
    [self.codeButton setTitle:kYQLS(@"发送验证码") forState:(UIControlStateNormal)];
    if ([sender.currentTitle isEqualToString:kYQLS(@"邮箱找回")]) {
        self.selectOperateType = 2;
    }else{
        self.selectOperateType = 1;
    }
    MYRegisterFindPasswordTextFieldCell *accountCell = (MYRegisterFindPasswordTextFieldCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    accountCell.textField.text = @"";
    MYRegisterFindPasswordCodeCell *codeCell = (MYRegisterFindPasswordCodeCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    codeCell.textField.text = @"";
    [self.listTableView reloadData];
}

-(void)selectPhoneAreaCode {
    [self.view endEditing:true];
    ws(self);
    [AreaCodeModel getAreaCode:^(NSArray<AreaCodeModel *> * codeModelArr) {
        NSMutableArray *localeArr = [NSMutableArray array];
        NSMutableArray *localeCodeArr = [NSMutableArray array];
        for (AreaCodeModel *codeModel in codeModelArr) {
            NSString * showTitle = [NSString stringWithFormat:@"%@ +%@",codeModel.zh,codeModel.code];
            if ([[[ZBLocalized sharedInstance] currentLanguage] isEqualToString:@"en"]) {
                showTitle = [NSString stringWithFormat:@"%@ +%@",codeModel.en,codeModel.code];
            }
            
            
            [localeArr addObject:showTitle];
            [localeCodeArr addObject:codeModel.code];
        }
        
        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:localeArr.copy defaultSelValue:self.defaultLocale isAutoSelect:NO themeColor:kAPPThemeColor resultBlock:^(id selectValue) {
            self.defaultLocale = selectValue;
            MYLoginBaseTextFieldPhoneCell *cell = (MYLoginBaseTextFieldPhoneCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            
            NSInteger index = [localeArr indexOfObject:selectValue];
            weakself.mobileAreaCode = localeCodeArr[index];
            
            cell.leftLb.text = [NSString stringWithFormat:@"+%@",weakself.mobileAreaCode];
            [weakself.listTableView reloadData];
        } cancelBlock:^{
            
        }];
        
    }];
}

#pragma mark - 发送验证码
- (void)sendCodeClick:(UIButton *)button
{
    MYRegisterFindPasswordTextFieldCell *phoneCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    MYRegisterFindPasswordCodeCell *codeCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    if (self.selectOperateType == 1) {
        if (phoneCell.textField.text.length == 0) {
            [MBProgressHUD showSuccess:kYQLS(@"请输入手机号")];
            return;
        }
//        else{
//            BOOL isValuate = [YQPInsureValidate validateMobile:phoneCell.textField.text];
//            if (!isValuate) {
//                [MBProgressHUD showSuccess:@"请输入有效手机号"];
//                return;
//            }
//        }
        
        NSMutableDictionary *dic = NSMutableDictionary.new;
        NSString *url = kGET_CODE_SMS_international_URL;
        dic[@"phone"] = [self.mobileAreaCode stringByAppendingString:phoneCell.textField.text];
        if ([self.mobileAreaCode isEqualToString:@"86"]) {
            url = kGET_CODE_SMS_URL;
            dic[@"phone"] = phoneCell.textField.text;
        }
        [YQPNetWorkingManager sendGetRequest:url parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            [MBProgressHUD showSuccess:kYQLS(@"发送成功")];
            [self.codeTimer start];
            //codeCell.textField.text = responseObject.data;
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            
        }];
        
    }else
    {
        if (phoneCell.textField.text.length == 0) {
            [MBProgressHUD showSuccess:kYQLS(@"请输入邮箱")];
            return;
        }else{
            BOOL isValuate = [YQPInsureValidate validateEmail:phoneCell.textField.text];
            if (!isValuate) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入有效邮箱")];
                return;
            }
        }
        
        NSMutableDictionary *dic = NSMutableDictionary.new;
        dic[@"email"] = phoneCell.textField.text;
        [YQPNetWorkingManager sendGetRequest:@"/api/send/mail" parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            [MBProgressHUD showSuccess:kYQLS(@"发送成功")];
            [self.codeTimer start];
            //codeCell.textField.text = responseObject.data;
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            
        }];
    }
    

}

#pragma mark 计时器KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"time"]) {
        NSInteger seconds = [[change objectForKey:@"new"] integerValue];
        NSString *time = [NSString stringWithFormat:@"%zdS",60-seconds];
        self.codeButton.enabled = NO;
        [self.codeButton setTitle:time forState:UIControlStateDisabled];
        
        if ([time isEqualToString:@"0S"]) {
            [self.codeTimer stop];
            self.codeButton.enabled = YES;
            [self.codeButton setTitle:kYQLS(@"重新获取") forState:(UIControlStateNormal)];
            [self.listTableView reloadData];
        }
    }
}

#pragma mark-- lazy
- (Calculagraph *)codeTimer {
    if (!_codeTimer) {
        _codeTimer = [[Calculagraph alloc] init];
        [_codeTimer addObserver:self forKeyPath:@"time" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _codeTimer;
}
#pragma mark-- lazy
- (void)dealloc {
    [self.codeTimer removeObserver:self forKeyPath:@"time"];
}
@end
